import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 
 * @author pfister
 * 
 */
public class ClientSocket {
	
	private String hostname;
	private int serverPort;

	private PrintWriter out;
	private BufferedReader in;
	private Socket socket;
	
	public ClientSocket(String host, int port) {
		super();
		this.hostname = host;
		this.serverPort = port;
	}

	public void init() throws UnknownHostException, IOException {
		socket = new Socket(hostname, serverPort);
		System.out.println("Connected to server");
		in = new BufferedReader(new InputStreamReader(
				socket.getInputStream()));
		out = new PrintWriter(socket.getOutputStream(), true); // autoflush
	}

	public void end() throws InterruptedException, IOException {
		System.out.println("closing connection - terminated");
		if (in != null)
			in.close();
		if (out != null)
			out.close();
	}

	public String send(String cmd)  {
		try {
			return doSend(cmd);
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}
	
	private String doSend(String cmd) throws InterruptedException, IOException {
		String result = null;
		if (socket.isClosed()) {
			System.out.println("server is down");
			return result;
		}
		out.println(cmd);
		result = in.readLine();
		if (result == null) 
			System.out.println("server is down");
		 else
		    System.out.println(result);
		return result;
	}

}
